<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace NanQi\Hope\Di;

use Hyperf\Config\Config;
use Hyperf\Config\ProviderConfig;
use Psr\Container\ContainerInterface;
use Symfony\Component\Finder\Finder;

class ConfigFactory extends \Hyperf\Config\ConfigFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $configDir = BASE_PATH . '/config';
        $configPath = $configDir . '/_config.php';
        if (is_dir($configDir) && file_exists($configPath)) {
            $config = $this->readConfig($configPath);
        } else {
            $config = [];
        }

        $autoloadPath = BASE_PATH . '/config/autoload';
        if (is_dir($autoloadPath)) {
            $autoloadConfig = $this->readPaths([$configDir, $autoloadPath]);
        } else if (is_dir($configDir)) {
            $autoloadConfig = $this->readPaths([$configDir]);
        } else {
            $autoloadConfig = [];
        }

        $merged = array_merge_recursive(ProviderConfig::load(), $config, ...$autoloadConfig);
        return new Config($merged);
    }

    private function readConfig(string $configPath): array
    {
        $config = [];
        if (file_exists($configPath) && is_readable($configPath)) {
            $config = require $configPath;
        }
        return is_array($config) ? $config : [];
    }

    private function readPaths(array $paths)
    {
        $configs = [];
        $finder = new Finder();
        $finder->files()->in($paths)->name('*.php');
        foreach ($finder as $file) {
            if ($file->getBasename('.php') != '_config') {
                $configs[] = [
                    $file->getBasename('.php') => require $file->getRealPath(),
                ];
            }
        }
        return $configs;
    }
}
